package com.yaodian100.ec.meeting.service.impl;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.google.gdata.client.calendar.CalendarQuery;
import com.google.gdata.client.calendar.CalendarService;
import com.google.gdata.data.DateTime;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.data.calendar.CalendarEventEntry;
import com.google.gdata.data.calendar.CalendarEventFeed;
import com.google.gdata.data.extensions.When;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;
import com.yaodian100.ec.meeting.service.GoogleCalService;

public class GoogleCalServiceImpl implements GoogleCalService {
	private final Log log = LogFactory.getLog(GoogleCalServiceImpl.class);
	private String username = "";
	private String password = "";

	public String addEvent(String subject, String title, String startTime, String endTime, String eventFeedUrl)
			throws NumberFormatException, MalformedURLException, ServiceException, IOException {
		CalendarService service = new CalendarService("demo-CalendarFeedDemo-1");
		String msg = "";
		URL url = new URL(eventFeedUrl);
		// 登入
		try {
			service.setUserCredentials(username, password);

			CalendarQuery myQuery = new CalendarQuery(url);
			myQuery.setMinimumStartTime(DateTime.parseDateTime(startTime));
			myQuery.setMaximumStartTime(DateTime.parseDateTime(endTime));

			CalendarEventFeed resultFeed = service.query(myQuery, CalendarEventFeed.class);

			if (resultFeed.getEntries().size() == 0) {
				try {
					CalendarEventEntry myEntry = new CalendarEventEntry();
					myEntry.setContent(new PlainTextConstruct(title));
					myEntry.setTitle(new PlainTextConstruct(subject));

					When eventTimes = new When();
					eventTimes.setStartTime(DateTime.parseDateTime(startTime));
					eventTimes.setEndTime(DateTime.parseDateTime(endTime));
					myEntry.addTime(eventTimes);
					CalendarEventEntry insertedEntry2 = service.insert(url, myEntry);
					msg = "預約成功";
				} catch (Exception e1) {
					msg = "預約失敗";
					log.info(e1.toString());
				}
			} else {
				msg = "此時段已有預約";
				log.info("此時段已有預約");
			}
		} catch (AuthenticationException e) {
			msg = "登入錯誤";
			log.info(msg + ";" + e.toString());
		}
		return msg;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

}
